import 'package:eh_mobile/common/utils/index.dart';
import 'package:eh_mobile/common/values/index.dart';
import 'package:eh_mobile/pages/main/homepage/model/home_device_model.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/light_card_overlay.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'ligth_brightness_bar.dart';

typedef LightCardItemCallback = void Function(bool value);
typedef LightCardItemRenameCallback = void Function(String value);

//灯光列表卡片
class LightCardItem extends StatefulWidget {
  const LightCardItem(this.lightCardModel,
      {super.key,
      this.editOpen = false,
      this.lightCardEditCallback,
      this.renameCallback,
      this.cardEventCallback,
      this.cardTapCallback});

  final HomeDeviceModelDevices lightCardModel;
  final bool editOpen; // 开启编辑
  // 编辑返回
  final LightCardItemCallback? lightCardEditCallback;

  // 重命名返回
  final LightCardItemRenameCallback? renameCallback;

  //卡片点击跳转
  final VoidCallback? cardTapCallback;

  // 卡片灯光控制
  final ValueChanged<bool>? cardEventCallback;

  @override
  State<LightCardItem> createState() {
    return LightCardItemState();
  }
}

class LightCardItemState extends State<LightCardItem> {
  final double _itemWidth = (1.sw - 24.r - 10.r) / 2.0;
  final double _itemHeight = (1.sw - 24.r - 10.r) / 2.0 * 0.77;

  late HomeDeviceModelDevices _lightCardModel;
  late GlobalKey _anchorKey;

  double _superHeight = 0;
  late bool _cardOpen = widget.lightCardModel.cardOpen!;

  @override
  void initState() {
    _anchorKey = GlobalKey(debugLabel: widget.lightCardModel.name);
    _lightCardModel = widget.lightCardModel;
    if (widget.lightCardModel.online == false) {
      widget.lightCardModel.hasEvent = false;
    }
    super.initState();
  }

  @override
  void didUpdateWidget(covariant LightCardItem oldWidget) {
    _lightCardModel = widget.lightCardModel;
    super.didUpdateWidget(oldWidget);
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        if (_superHeight > 0) {
          if (constraints.biggest.height >= _superHeight) {
            _cardOpen = true;
          } else {
            _cardOpen = false;
          }
        }

        _superHeight = constraints.biggest.height;

        return widget.editOpen
            ? _buildMainWidget()
            : GestureDetector(
                onTap: () {
                  if (widget.lightCardModel.online == false) {
                    return;
                  }
                  if (widget.cardTapCallback != null) {
                    widget.cardTapCallback!();
                  }
                },
                onLongPress: () {
                  HapticFeedback.mediumImpact();
                  LightCardOverlay.show(
                    context,
                    offset: _anchorKey.position()!,
                    size: _anchorKey.size!,
                    deviceLListType: DeviceLListType.light,
                    lightCardModel: widget.lightCardModel,
                    lightCardOverlayCallback: (
                        {bool? isEdit, bool? isRename, name}) {
                      if (isEdit!) {
                        widget.lightCardEditCallback!(true);
                      } else if (isRename!) {
                        setState(() {
                          widget.lightCardModel.name = name;
                        });
                        widget.renameCallback!(name!);
                      }
                    },
                  );
                },
                child: _buildMainWidget());
      },
    );
  }

// 创建主要视图
  Widget _buildMainWidget() {
    return SizedBox(
      key: _anchorKey,
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
                color: widget.lightCardModel.hasEvent??false
                    ? const Color.fromRGBO(196, 196, 196, 1)
                    : const Color.fromRGBO(55, 55, 55, 1),
                borderRadius: BorderRadius.circular(25.r)),
          ),
          Positioned(
            top: _itemHeight - 60.r,
            left: 8.r,
            child: SizedBox(
              height: 50.r,
              width: _itemWidth - 16.r,
              child: AnimatedOpacity(
                opacity: _cardOpen ? 1 : 0,
                curve: _cardOpen ? Curves.easeInCirc : Curves.easeOutExpo,
                duration: const Duration(milliseconds: 300),
                child: LightBrightnessBar(
                    value: widget.lightCardModel.hasEvent!
                        ? widget.lightCardModel.brightness!
                        : 0,
                    backgroundColor: widget.lightCardModel.hasEvent!
                        ? const Color.fromRGBO(75, 75, 75, 1)
                        : const Color.fromRGBO(38, 38, 38, 1),
                    barColor: widget.lightCardModel.hasEvent!
                        ? const Color.fromRGBO(255, 255, 255, 1)
                        : const Color.fromRGBO(38, 38, 38, 1),
                    iconColor: const Color.fromRGBO(55, 55, 55, 1),
                    valueChanged: (value) {
                      setState(() {
                        widget.lightCardModel.brightness = value;
                      });
                    }),
              ).userInterface(!widget.editOpen ||
                  !widget.lightCardModel.hasEvent! ||
                  widget.lightCardModel.online!),
            ),
          ),
          Positioned(
            child: Container(
              height: _itemHeight / 2.0 - 8.r,
              decoration: BoxDecoration(
                  color: widget.lightCardModel.hasEvent!
                      ? const Color.fromRGBO(196, 196, 196, 1)
                      : const Color.fromRGBO(55, 55, 55, 1),
                  borderRadius: BorderRadius.circular(25.r)),
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(8, 8, 0, 0).r,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 50.w,
                  height: 50.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25).w,
                    color: widget.lightCardModel.hasEvent!
                        ? const Color.fromRGBO(50, 50, 50, 1)
                        : const Color.fromRGBO(38, 38, 38, 1),
                  ),
                  child: IconButton(
                    onPressed: () {
                      if (widget.editOpen || !widget.lightCardModel.online!) {
                        return;
                      }
                      setState(() {
                        widget.lightCardModel.hasEvent =
                            !widget.lightCardModel.hasEvent!;
                      });

                      widget
                          .cardEventCallback!(widget.lightCardModel.hasEvent!);
                    },
                    iconSize: 28.r,
                    icon: SvgPicture.asset(
                      (widget.lightCardModel.model == 98 &&
                              widget.lightCardModel.config?.type == 'lights')
                          ? 'assets/svgs/light_control/ic_lampgroup.svg'
                          : SVGImage.cIcLightingSvg,
                      color: widget.lightCardModel.hasEvent!
                          ? const Color.fromRGBO(255, 234, 154, 1)
                          : const Color.fromRGBO(255, 255, 255, 0.25),
                    ),
                  ),
                ),
                8.sizedBoxWidth,
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [_buildLightNameText(), _buildLightStateText()],
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 创建灯光名称文字
  Widget _buildLightNameText() {
    Color textColor = widget.lightCardModel.hasEvent!
        ? const Color.fromRGBO(50, 50, 50, 1)
        : const Color.fromRGBO(255, 255, 255, 0.5);
    if (widget.lightCardModel.online == false) {
      textColor = const Color.fromRGBO(255, 255, 255, 0.2);
    }

    return Container(
      padding: EdgeInsets.only(top: 1, right: widget.editOpen ? 20 : 4).r,
      height: 21.w,
      // width: 44,
      child: Text(
        widget.lightCardModel.name!,
        textAlign: TextAlign.left,
        overflow: TextOverflow.ellipsis,
        softWrap: true,
        maxLines: 1,
        style: 16.ts.copyWith(color: textColor),
      ),
    );
  }

  // 创建灯光状态文字
  Widget _buildLightStateText() {
    String stateText = widget.lightCardModel.hasEvent!
        ? '打开 - ${(widget.lightCardModel.brightness! * 100).round()}%'
        : '关闭';
    Color textColor = widget.lightCardModel.hasEvent!
        ? const Color(0XFF323232)
        : const Color.fromRGBO(255, 255, 255, 0.38);

    Color backgroundColor = Colors.transparent;
    if (widget.lightCardModel.online == false) {
      stateText = ' 不可用 ';
      textColor = const Color.fromRGBO(255, 138, 100, 1);
      backgroundColor = const Color.fromRGBO(255, 138, 100, 0.25);
    }

    return Container(
        margin: const EdgeInsets.only(top: 5).r,
        height: 18.r,
        decoration: BoxDecoration(
            color: backgroundColor, borderRadius: BorderRadius.circular(7)),
        child: Text(
          overflow: TextOverflow.ellipsis,
          softWrap: false,
          maxLines: 1,
          stateText,
          style: 14.ts.copyWith(color: textColor),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return _buildView(context);
  }
}
